package net.sunzc.base.alipay;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import com.alipay.sdk.app.PayTask;
import com.socks.library.KLog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class AliPay extends AsyncTask<OrderModel, Void, String> {
    /**
     * 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
     */
    private static final String SUCCESS = "9000";
    /**
     * “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
     */
    private static final String ON_SURE = "8000";
    //商户PID
    private static final String PARTNER = "2088711810672445";
    //商户收款账号
    private static final String SELLER = "849877781@qq.com";
    //商户私钥，pkcs8格式

    private static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM6MFHSJ9PgEES0dLh3bTCAjyMGeKPRw9p/v1aBNOAjfdReJU5mnusW853k8NM3XEskRi6AXsd1W5/8aZkpaQ3qvtBkNYmvyJw0ys+hUIZ3JEHQb+psQ1S/JWbiwEsup7Os0rwLAjrl/fVwQ/OjftQwKFmrq+hXZxalaCJUvVI0fAgMBAAECgYEAkObTHuL92dU4m5bCGK4VnOKd379uafap/pBKJXim3AqwYb+0x7JVJI4fMf1b6iB9jFPjyX92B5sFjQFfS8BBX5f/NgdpDWU6JBhUsgJizvRpxl0PgUKSu0ZirtSVC0Q7I4H3DcWYNz9Uzfy0V8AMic7pujjhxwHW/hyDZHgYeWkCQQD6XDP+IJ2kBxoM+CLdvbHk0M3wMnx7htyNS4b5cPLsRg1tmkI0OfrP+tUX5+l1y3PMXLV80S4/4pmvglZ5jA8VAkEA0zM2brbkEaXTNOsooMwXXvJVRNU4HLEkLFZTkimZ1mvuM+NIK4DpP/oZKeDOacKyirYRBUI2PXmPGR/Wn+3YYwJBANCYOgmmizG7aQ0dQY+XGb0X7D4REn6pYuGm6BK09PG/fDixqi9xj3Px/dIpO+8VUKoZJG2Wq/42gu4knoAvHfECQF403NXbzLW2gxR6xJ+dCdu3OqO+fA4IUftY8mQjHFTRxentOrb1BJYeB/VvKoNwblWDSupOk4UuYM8zLXgfDsMCQBbadtjg2G6DDF2FB8FAjuXphBopn2aBDA4Y20Q9D6hcyUnYvX/mVhMjHdSOimkwYSLHeBXgFV+P6mUiMOwVMOo=";
    //支付宝公钥
    private static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcRAKG98AoF+dSLxplfeMUL9+7wuRlasTuXhIr4uf2oQeBG9Cc23Hc5KIBJAAypr9nvuKQCv15UuOz6E6ww+b4Z3eEUpxtEKpK0G3snGeL5Fh39prFhpsCxzoBuHxsfDE5dTRRmt02qiWIgVHNnH1dfi++0VeQeBoW1euX8DuxnwIDAQAB";

    private final Context mContext;
    private final PayListener mPayListener;
    private final OrderModel mOrder;
    private final ProgressDialog dialog;

    public static void startPay(Context context, OrderModel order, PayListener listener) {
        AliPay aliPay = new AliPay(context, order, listener);
        aliPay.execute();
    }

    private AliPay(Context context, OrderModel order, PayListener listener) {
        this.mContext = context;
        this.mPayListener = listener;
        this.mOrder = order;
        dialog = ProgressDialog.show(mContext, "提示",
                "正在支付……");
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public void execute() {
        execute(mOrder);
    }

    private String getOrderInfo(OrderModel order) {
        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + order.getOrderNo() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + order.getObjectName() + "\"";

        // 商品详情
//        orderInfo += "&body=" + "\"" + order.getList ().toString () + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + order.getAmount() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + order.getNoticeUrlForAli()
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空,网页版需要
//		orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
//		 orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
                Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (dialog != null && !dialog.isShowing())
            dialog.show();
    }

    @Override
    protected String doInBackground(OrderModel... params) {
        // 订单
        String orderInfo = getOrderInfo(params[0]);
        // 对订单做RSA 签名
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 完整的符合支付宝参数规范的订单信息
        String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();
        // 构造PayTask 对象
        PayTask alipay = new PayTask((Activity) mContext);
        // 调用支付接口，获取支付结果
        return alipay.pay(payInfo);
    }

    @Override
    protected void onPostExecute(String s) {
        PayResult payResult = new PayResult(s);
        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
        String resultInfo = payResult.getResult();
        KLog.i("支付结果：" + resultInfo);
        String resultStatus = payResult.getResultStatus();
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
        switch (resultStatus) {
            case SUCCESS:
                ViewUtils.showToast("支付成功");
                if (mPayListener != null)
                    mPayListener.onSuccess(mOrder);
                break;
            case ON_SURE:
                ViewUtils.showToast("支付结果确认中。。。。。");
                break;
            default://判断resultStatus 为非“9000”则代表可能支付失败
                ViewUtils.showToast("支付失败" + resultInfo);
                break;
        }

    }
}
